package com.taiyi.renaissancemall.ui.mine.verified;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.PersistableBundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.FileProvider;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.taiyi.renaissancemall.R;
import com.taiyi.renaissancemall.Utils.IDCardValidate;
import com.taiyi.renaissancemall.Utils.RegexUtil;
import com.taiyi.renaissancemall.Utils.ToastUtils;
import com.taiyi.renaissancemall.base.BaseActivity;
import com.taiyi.renaissancemall.base.MyApp;

import org.devio.takephoto.app.TakePhoto;
import org.devio.takephoto.app.TakePhotoActivity;
import org.devio.takephoto.app.TakePhotoImpl;
import org.devio.takephoto.model.InvokeParam;
import org.devio.takephoto.model.TContextWrap;
import org.devio.takephoto.model.TResult;
import org.devio.takephoto.permission.InvokeListener;
import org.devio.takephoto.permission.PermissionManager;
import org.devio.takephoto.permission.TakePhotoInvocationHandler;

import java.io.File;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;

//实名页面
public class VerifiedActivity extends BaseActivity<VerifiedView, VerifiedPresent> implements VerifiedView, TakePhoto.TakeResultListener, InvokeListener {

    @BindView(R.id.backIv)
    ImageView backIv;
    @BindView(R.id.titleTv)
    TextView titleTv;
    @BindView(R.id.rightTitleTv)
    TextView rightTitleTv;
    @BindView(R.id.topB)
    TextView topB;
    @BindView(R.id.actualName)
    TextView actualName;
    @BindView(R.id.nameEt)
    EditText nameEt;
    @BindView(R.id.identityNumber)
    TextView identityNumber;
    @BindView(R.id.identityNumberEt)
    EditText identityNumberEt;
    @BindView(R.id.tvLeft)
    TextView tvLeft;
    @BindView(R.id.portraitFaceIv)
    ImageView portraitFaceIv;
    @BindView(R.id.v1)
    View v1;
    @BindView(R.id.tvRight)
    TextView tvRight;
    @BindView(R.id.content)
    TextView content;
    @BindView(R.id.nationalEmblemIv)
    ImageView nationalEmblemIv;
    @BindView(R.id.v2)
    View v2;
    @BindView(R.id.commitVerfiedTv)
    TextView commitVerfiedTv;
    @BindView(R.id.top)
    ConstraintLayout top;
    private String name = "";
    private String num = "";
    private String frount_photo = "";
    private String reverse_photo = "";
    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private static final String TAG = TakePhotoActivity.class.getName();
    private String mImagePath = Environment.getExternalStorageDirectory() + "";
    private String mImageName = "/wanlimall/" + System.currentTimeMillis() + ".jpg";
    private String path = "";
    private Uri imageUri = null;
    private TextView headChangePopupBlack;
    private Button takePhotoBtn;
    private Button pickPhotoBtn;
    private Button cancelBtn;
    private BaseBottomView bottomView;
    private boolean isXiangCe = false;
    private String iconPath = "";
    private int faceId = 0;
    private String getOSSUrl = "";
    private String isThrough;//-1未实名 0.认证未通过 1.认证中 2.认证通过

    @Override
    protected int getLayoutId() {
        return R.layout.activity_verified;
    }

    @Override
    public VerifiedPresent initPresenter() {
        return new VerifiedPresent();
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);

        titleTv.setText(getString(R.string.verified));

        //设置点击图片的弹框显示
        bottomView = new BaseBottomView(this, R.layout.act_photo);
        headChangePopupBlack = ((TextView) bottomView.findViewById(R.id.headChangePopupBlackId));
        takePhotoBtn = (Button) bottomView.findViewById(R.id.takePhotoBtnId);
        pickPhotoBtn = (Button) bottomView.findViewById(R.id.pickPhtotBtnId);
        cancelBtn = (Button) bottomView.findViewById(R.id.cancel_btnId);
        bottomView.setCancelable(true);

        isThrough = getIntent().getStringExtra("isThrough");
        //-1未实名 0.认证未通过 1.认证中 2.认证通过
        /*
        实名认证,认证中,应该能进入实名认证页面,可以看,不可以修改;按钮不可以点击;并且按钮文字显示成状态的文字;认证中;
未认证      可以上传,按钮可以点击
认证中  只能查看,不能修改,按钮不可以点击;按钮文字显示成认证中
认证未通过      可以上传,按钮可以点击重新上传
认证已通过    只能查看,不能修改,按钮不可以点击;按钮文字显示成认证通过
         */
        if ("-1".equals(isThrough)) {
            commitVerfiedTv.setText("提交审核");
        } else if ("0".equals(isThrough)) {
            commitVerfiedTv.setText("重新提交审核");
            SharedPreferences sharedPreferences = getSharedPreferences("isThrough", Context.MODE_PRIVATE);
            name = sharedPreferences.getString("name", "");
            num = sharedPreferences.getString("idCard", "");
            frount_photo = sharedPreferences.getString("leftIcon", "");
            reverse_photo = sharedPreferences.getString("rightIcon", "");
            nameEt.setText(name);
            identityNumberEt.setText(num);
            Glide.with(VerifiedActivity.this).load(frount_photo).into(portraitFaceIv);
            Glide.with(VerifiedActivity.this).load(reverse_photo).into(nationalEmblemIv);
        } else if ("1".equals(isThrough)) {
            commitVerfiedTv.setText("提交审核");
        } else if ("2".equals(isThrough)) {
            commitVerfiedTv.setText("提交审核");
        }
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(top).statusBarDarkFont(false, 1.0f).init();
    }

    @Override
    protected void initData() {
        //关闭选择界面
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomView.dismiss();
            }
        });

        //选择相册
        pickPhotoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isXiangCe = true;
                imageUri = getImageCropUri();
                //从相册中选取不裁剪
                takePhoto.onPickFromGallery();
            }
        });

        //选择拍照
        takePhotoBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isXiangCe = false;
                imageUri = getImageCropUri();

                //仅仅拍照不裁剪
                takePhoto.onPickFromCapture(imageUri);
            }
        });

        headChangePopupBlack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomView.dismiss();
            }
        });
    }

    @Override
    public void initEvent() {
    }

    @Override
    public void VerifiedSuccess(String msg_cn) {
        hideProgress();
        ToastUtils.showLongToast(msg_cn);
        SharedPreferences sharedPreferences = getSharedPreferences("isThrough", Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString("name", name);
        edit.putString("idCard", num);
        edit.putString("leftIcon", frount_photo);
        edit.putString("rightIcon", reverse_photo);
        edit.apply();
        finish();
    }

    @Override
    public void VerifiedFailure(String msg) {
        hideProgress();
        ToastUtils.showLongToast(msg);
    }

    @OnClick({R.id.portraitFaceIv, R.id.nationalEmblemIv, R.id.commitVerfiedTv, R.id.backIv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.backIv:
                finish();
                break;
            case R.id.portraitFaceIv:
                //正面
                faceId = 1;
                bottomView.show();
                break;
            case R.id.nationalEmblemIv:
                //反面
                faceId = 2;
                bottomView.show();
                break;
            case R.id.commitVerfiedTv:
                /**
                 *   identification_name
                 * 姓名
                 * query
                 * true
                 * string
                 *        identification_number
                 * 身份证号
                 * query
                 * true
                 * string
                 *        front_photo
                 * 证件正面照
                 * query
                 * true
                 * string
                 *        reverse_photo
                 * 证件背面照
                 */
                name = nameEt.getText().toString().trim();
                num = identityNumberEt.getText().toString().trim();
                //进行非空和身份证验证并提交
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShortToast("请输入姓名");
                    return;
                }
                if (TextUtils.isEmpty(num)) {
                    ToastUtils.showShortToast("请输入身份证号");
                    return;
                }
                if (!RegexUtil.checkIdCard(num)) {
                    ToastUtils.showShortToast("请输入正确的身份证号");
                    return;
                }
                if (!IDCardValidate.validate_effective(num)) {
                    ToastUtils.showShortToast("请输入正确的身份证号");
                    return;
                }
                if (TextUtils.isEmpty(frount_photo)) {
                    ToastUtils.showShortToast("请上传正面照");
                    return;
                }
                if (TextUtils.isEmpty(reverse_photo)) {
                    ToastUtils.showShortToast("请上传国徽照");
                    return;
                }
                showProgress();
                presenter.getVerified(name, num, frount_photo, reverse_photo);
                break;
        }
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);
    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }

    @Override
    public void takeSuccess(TResult result) {
        if (bottomView.isShowing()) {
            bottomView.dismiss();
        }
        iconPath = result.getImage().getOriginalPath();

        if (isXiangCe) {
            uploadFileToOSS(iconPath, faceId);
        } else {
            uploadFileToOSS(path, faceId);
        }
        Log.i(TAG, "takeSuccess：" + result.getImage().getCompressPath() + "==" + result.getImage().getOriginalPath());
    }

    /**
     * 上传OSS
     *
     * @param iconPath 文件路径
     */
    private void uploadFileToOSS(String iconPath, int faceId) {
        String[] strings = iconPath.split("/");
        String name = strings[strings.length - 1];
        OSSClient ossClient = MyApp.getOssClient();
        // 构造上传请求。
        PutObjectRequest put = new PutObjectRequest("wlshop-app", name, iconPath);

        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = ossClient.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Log.d("PutObject", "UploadSuccess");
                        Log.d("ETag", result.getETag());
                        Log.d("RequestId", result.getRequestId());
                        getOSSUrl = ossClient.presignPublicObjectURL("wlshop-app", name);
                        Log.d("servercallback", "1--" + getOSSUrl);
                        if (faceId == 1) {
                            Glide.with(VerifiedActivity.this).load(iconPath).into(portraitFaceIv);
                            frount_photo = getOSSUrl;
                        } else if (faceId == 2) {
                            Glide.with(VerifiedActivity.this).load(iconPath).into(nationalEmblemIv);
                            reverse_photo = getOSSUrl;
                        }
                    }
                });
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                ToastUtils.showLongToast("图片上传异常");
                // 请求异常。
                if (clientExcepion != null) {
                    // 本地异常，如网络异常等。
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常。
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });
        // task.cancel(); // 可以取消任务。
        // task.waitUntilFinished(); // 等待任务完成。
    }

    @Override
    public void takeFail(TResult result, String msg) {
        Log.i(TAG, "takeFail:" + msg);
    }

    @Override
    public void takeCancel() {
        Log.i(TAG, getResources().getString(R.string.msg_operation_canceled));
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this), invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    //获得照片的输出保存Uri
    private Uri getImageCropUri() {
        String mImageName = "/wanlimall/" + System.currentTimeMillis() + ".jpg";
        File file = new File(mImagePath, mImageName);
        path = mImagePath + mImageName;
        if (!file.getParentFile().exists()) file.getParentFile().mkdirs();
        Uri uri;

//        if (Build.VERSION.SDK_INT >= 24) {
//            uri = FileProvider.getUriForFile(this, "com.taiyi.renaissancemall.provider", new File(path));
//        } else {
//            uri = Uri.fromFile(new File(path));
//        }
        return Uri.fromFile(file);
//        return uri;
    }

}
